package com.wfh.mianshiji.ws.handler;

import cn.hutool.json.JSONUtil;
import com.wfh.mianshiji.common.ErrorCode;
import com.wfh.mianshiji.exception.BusinessException;
import com.wfh.mianshiji.ws.model.Message;
import com.wfh.mianshiji.ws.model.enums.MessageTypeEnum;
import jakarta.websocket.Session;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

/**
 * @Title: HeartbeatHandler
 * @Author wangfenghuan
 * @Package com.wfh.mianshiji.ws.handler
 * @Date 2025/10/31 16:09
 * @description:
 */
@Component
public class HeartbeatHandler implements BaseHandler{
    @Override
    public MessageTypeEnum getMessageType() {
        return MessageTypeEnum.HEARTBEAT;
    }

    /**
     * 心跳处理器
     * @param message
     * @param session
     */
    @Override
    public void handle(Message message, WebSocketSession session) {
        Message pong = new Message();
        pong.setType(MessageTypeEnum.HEARTBEAT.getValue());
        if (session.isOpen()){
            try {
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(pong)));
            } catch (IOException e) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }
}
